package com.shyroke.daydayzhuansvc.util;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.BufferedImageLuminanceSource;
import com.google.zxing.*;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageUtils {

    //过滤的图片路径前缀，必须要是完整路径的前缀，即包含协议类型http或者https
    public static String[] filter_url = {"http://wpa.qq.com"} ;


    /**
     * //检测图片链接是否需要过滤
     * @param url
     * @return
     */
    public static boolean filterUrl(String url) {

       boolean flag = false;
       for(String filter : filter_url){
           if(url.startsWith(filter)){
               flag = true;
               break;
           }
       }
       return  flag;
    }

    public static boolean isQRCodeInImage(String imagePath) {
        if(StrUtil.isBlank(imagePath)) {
            return false;
        }
        try {
            URL url = new URL(imagePath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            conn.setRequestProperty("User-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36");
            InputStream inputStream = conn.getInputStream();// 通过输入流获取图片数据
            BufferedImage image = ImageIO.read(inputStream);
            LuminanceSource luminanceSource = new BufferedImageLuminanceSource(image);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));

            Result result = new MultiFormatReader().decode(binaryBitmap);
            return result != null;
        } catch (NotFoundException e) {
            // NotFoundException is thrown when QR code is not found in the image
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
